import { defineStore } from 'pinia'
import axios from 'axios'

const API_BASE_URL = 'http://localhost:8080'; // 后端 API 地址

export const useMapStore = defineStore('map', {
  state: () => ({
    pois: [], // 存储校园POI
    startPoint: null, // { id, name, lat, lng }
    endPoint: null, // { id, name, lat, lng }
    currentRouteData: null, // 高德地图返回的路线数据
    loading: false,
    error: null,
  }),
  actions: {
    async fetchPOIs() {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.get(`${API_BASE_URL}/pois`);
        this.pois = response.data;
      } catch (err) {
        this.error = 'Failed to fetch POIs: ' + err.message;
        console.error(err);
      } finally {
        this.loading = false;
      }
    },
    setStartPoint(poi) {
      this.startPoint = poi;
    },
    setEndPoint(poi) {
      this.endPoint = poi;
    },
    clearSP() {
      this.startPoint = null;
    },
    clearEP() {
      this.endPoint = null;
    },
    clearPs() {
      this.startPoint = null;
      this.endPoint = null;
      this.currentRouteData = null;
    },
    async planRoute(startCoords, endCoords) {
      this.loading = true;
      this.error = null;
      try {
        // 直接调用后端路由规划API
        const response = await axios.get(`${API_BASE_URL}/route/walking`, {
          params: {
            startLat: startCoords.lat,
            startLng: startCoords.lng,
            endLat: endCoords.lat,
            endLng: endCoords.lng,
          },
        });
        this.currentRouteData = response.data;
        console.log("Route planned successfully:", response.data);
      } catch (err) {
        this.error = 'Failed to plan route: ' + err.message;
        console.error("Error planning route:", err);
      } finally {
        this.loading = false;
      }
    }
  },
});